package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import model.LyTable;
import model.User;

public class DB {
	Connection ct;
	PreparedStatement pstmt;

	public DB() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			ct = DriverManager
					.getConnection("jdbc:mysql://localhost:3306/simplemessage",
							"root", "root");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public User checkUser(String username, String password) {
		try {
			pstmt = ct
					.prepareStatement("select * from usertable where username=? and password=?");
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			ResultSet rs = pstmt.executeQuery();
			User user = new User();
			while (rs.next()) {
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				return user;
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public ArrayList findMessage() {
		try {
			ArrayList al = new ArrayList();
			pstmt = ct.prepareStatement("select * from messagetable");
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				LyTable message = new LyTable();
				message.setId(rs.getInt(1));
				message.setUserId(rs.getInt(2));
				message.setDate(rs.getDate(3));
				message.setTitle(rs.getString(4));
				message.setContent(rs.getString(5));
				al.add(message);
			}
			return al;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	public String getUserName(int userID){
		try{
			pstmt=ct.prepareStatement("select username from usertable where userid=?");
			pstmt.setInt(1, userID);
			ResultSet rs=pstmt.executeQuery();
			return rs.getString(1);
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
